package com.lvm.app.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.crypto.digest.MD5;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;


public class CreateMd5 {
    public static StringBuilder createMd5(@NotNull final MultipartFile file)
            throws Exception {
        StringBuilder sb = new StringBuilder();
        //生成MD5实例
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        InputStream inputStream = file.getInputStream();
        int available = inputStream.available();
        byte[] bytes = new byte[available];
        md5.update(bytes);
        for (byte by : md5.digest()) {
            //将生成的字节MD5值转换成字符串
            sb.append(String.format("%02X", by));
        }
        return sb;
    }
    public static StringBuilder createMd5(@NotNull final File file)
            throws Exception {
        StringBuilder sb = new StringBuilder();
        //生成MD5实例
        InputStream inputStream = null;
        try{
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            inputStream =new FileInputStream(file);
            byte[] bytes = new byte[819600];
            int length;
            while ((length = inputStream.read(bytes)) != -1) {
                md5.update(bytes,0,length);
            }
            for (byte by : md5.digest()) {
                //将生成的字节MD5值转换成字符串
                sb.append(String.format("%02X", by));
            }
        }catch(Exception e){

        }finally {
            if(inputStream!=null){
                inputStream.close();
            }
        }
        return sb;
    }


    public static void main(String[] args) throws Exception {


    }
}
